package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @Title: UserServiceImpl
 * @Author 张宇
 * @Package com.sky.service.impl
 * @Date 2025/10/3 18:07
 */


@Slf4j
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public User login(UserLoginDTO dto) {

        // 通过httpclient构造登录请求
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",dto.getCode());
        paramMap.put("grant_type","authorization_code");

        // 调用HttpClientUtil工具类,发送请求
        String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        log.info("res={}",res);

        // 解析响应结果,获取openid
        JSONObject obj = JSON.parseObject(res);
        String openId = (String) obj.get("openid");
        if (openId == null){
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }

        // 判断是否为新用户
        User user = userMapper.selectByOpenid(openId);
        if (user == null){
            // 新用户初始化数据到user表中
            user = new User();
            user.setOpenid(openId);
            user.setName(openId.substring(0,5));
            user.setCreateTime(LocalDateTime.now());

            userMapper.insert(user);
        }


        // 否则直接返回user对象数据
        return user;
    }
}
